package com.dongdongshop.filter;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dongdongshop.data.Result;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    //过滤器功能
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (1==1)return chain.filter(exchange);
       //通过请求取出token,一般通过请求头
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("AutharizeToken");
        //如果token不存在,没登录,说明无效的token
        if (token == null || "".equals(token)){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            //这里在返回头添加编码，否则中文会乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            byte[] bytes = JSONObject.toJSONBytes(new Result<>(4,"无效的"), SerializerFeature.WriteMapNullValue);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        }
        return null;
    }

    //如果网关有多个过滤器此数字表示过滤器执行的顺序,数字越小越限执行
    @Override
    public int getOrder() {
        return 0;
    }
}
